package com.woniuxy.shirotest;

import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.stereotype.Component;

/**
 * @Author: ideaAdmin
 * TODO: Class
 * TODO: 继承AuthorizingRealm 实现自定义域
 * Date: 2022/2/22:19:06
 * Description:
 */

public class MyRealm extends AuthorizingRealm {
    /**
        * TODO:判断是否有某个角色或拥有某个权限
     *      PrincipalCollection 校长 就是用户名
    **/
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //获得用户名
         String username = (String) principals.getPrimaryPrincipal();

         //获得需要返回的授权器
        //通过数据库查询 然后用setRoles放入到授权器中 也可以setStringPermissions放入查找的所有权限
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.addRole("role1");
        simpleAuthorizationInfo.addRole("role2");
        simpleAuthorizationInfo.addStringPermission("user::add");
        simpleAuthorizationInfo.addStringPermission("user::del");

        return simpleAuthorizationInfo;
    }

    /**
        * TODO:判断用户是否登陆 AuthenticationToken里面可以获得提交的账户密码
    **/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken  usernamePasswordToken = (UsernamePasswordToken) token;

        //获得用户名
        String username = usernamePasswordToken.getUsername();
        String password = new String(usernamePasswordToken.getPassword());

        if(username.equals("root1")){
            //获得认证器 设置好属性 返回 让securityManager管理
            SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo
                    //用户名 密码 自定义域
                    (username+"这里返回校长", password, "MyRealm");

            //把凭证返回 让securityManager来进行管理
            return simpleAuthenticationInfo;
        }else {
            throw new AuthenticationException("账户或密码错误");
        }
    }
}
